import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:just_audio/just_audio.dart';

import '../components/translation_input.dart';
import '../components/language_selector.dart';
import '../components/bluetooth_status_bar.dart';
import '../services/ms_websocket_trans_service.dart';
import '../services/websocket_connection_manager.dart';
import '../services/translation_settings.dart';
import '../services/recorder_service.dart';
import '../services/foreground_recorder_service.dart';
import '../services/ble_service.dart';
import '../utils/permission_helper.dart';
import '../app_logger.dart';
import '../utils/audio_format_helper.dart';


class AudioTranslationTtsScreen extends StatefulWidget {
  const AudioTranslationTtsScreen({super.key});

  @override
  State<AudioTranslationTtsScreen> createState() => _AudioTranslationTtsScreenState();
}

class _AudioTranslationTtsScreenState extends State<AudioTranslationTtsScreen> with WidgetsBindingObserver {
  // 服务实例
  late MSWebSocketTransService _translationService; // 使用late声明，在initState中初始化
  final RecorderService _recorderService = RecorderService();
  final ForegroundRecorderService _foregroundService = ForegroundRecorderService();
  final BleService _bleService = BleService();
  final TextEditingController _textController = TextEditingController();
  final AudioPlayer _audioPlayer = AudioPlayer();

  // BLE录音状态监听
  StreamSubscription<RecordStatus>? _bleRecordStatusSubscription;

  // BLE连接状态监听
  StreamSubscription<void>? _bleConnectionStateSubscription;

  // 蓝牙连接状态
  bool _isBluetoothConnected = false;
  String _connectedDeviceName = '';

  // 状态管理
  bool _isConnected = false;
  bool _isRecording = false;
  bool _isTranslating = false;
  bool _isReconnecting = false;
  int _reconnectAttempts = 0;
  static const int _maxReconnectAttempts = 5;
  static const Duration _reconnectDelay = Duration(seconds: 3);

  // 语言设置（从TranslationSettings获取）
  String get _fromLanguage => TranslationSettings.instance.fromLanguage;
  set _fromLanguage(String value) => TranslationSettings.instance.fromLanguage = value;

  String get _toLanguage => TranslationSettings.instance.toLanguage;
  set _toLanguage(String value) => TranslationSettings.instance.toLanguage = value;

  // TTS设置（从TranslationSettings获取）
  bool get _autoPlayTts => TranslationSettings.instance.autoPlayTts;
  set _autoPlayTts(bool value) => TranslationSettings.instance.autoPlayTts = value;

  bool get _useMaleVoice => TranslationSettings.instance.useMaleVoice;
  set _useMaleVoice(bool value) => TranslationSettings.instance.useMaleVoice = value;

  bool get _onlyShowTranslation => TranslationSettings.instance.onlyShowTranslation;
  set _onlyShowTranslation(bool value) => TranslationSettings.instance.onlyShowTranslation = value;

  bool get _autoCopy => TranslationSettings.instance.autoCopy;
  set _autoCopy(bool value) => TranslationSettings.instance.autoCopy = value;

  // 服务器设置
  String _currentServerName = ''; // 简化为只显示当前服务器名称

  // 翻译结果
  String _lastTtsAudioUrl = '';
  String _currentTranslatedText = ''; // 当前显示的译文

  // TTS音频队列相关
  final List<String> _pendingTtsUrls = []; // 待播放的TTS音频队列
  final List<String> _allTtsUrls = []; // 保存所有的TTS音频URL，不会被消耗
  bool _isPlayingQueue = false; // 是否正在播放队列中的音频
  int _currentPlayingIndex = 0; // 当前播放的音频索引
  StreamSubscription? _playerSubscription; // 音频播放监听订阅

  // 累积文本片段
  final List<String> _recognizedSegments = []; // 累积的识别文本片段
  final List<String> _translatedSegments = []; // 累积的翻译文本片段
  bool _hasIncompleteSegment = false; // 是否有正在构建中的片段

  // 重连控制
  bool _shouldStopReconnecting = false; // 用于停止重连循环
  bool _isAppInBackground = false; // 应用是否在后台


  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this); // 添加生命周期监听
    _translationService = WebSocketConnectionManager.instance.getService(); // 从管理器获取服务

    // 初始化前台服务
    _foregroundService.init();

    // 设置前台服务动作回调
    _foregroundService.setOnForegroundServiceAction(_handleForegroundServiceAction);

    // 初始化BLE服务
    _initializeBleService();

    // 同步WebSocket连接状态（用于tab切换时的状态恢复）
    _syncWebSocketConnectionState();

    _initializeServices();
  }

  /// 初始化BLE服务
  Future<void> _initializeBleService() async {
    try {
      // 初始化BLE服务
      await _bleService.initialize();

      // 监听BLE录音状态变化
      _bleRecordStatusSubscription = _bleService.recordStatusStream.listen(_handleBleRecordStatus);

      // 监听BLE连接状态变化
      _bleConnectionStateSubscription = _bleService.connectionChangeStream.listen((_) {
        _updateBluetoothConnectionState();
      });

      // 初始化蓝牙连接状态
      _updateBluetoothConnectionState();

      log.d('🔵 BLE服务初始化成功');
    } catch (e) {
      log.d('🔵 BLE服务初始化失败: $e');
    }
  }

  /// 同步WebSocket连接状态（用于tab切换时状态恢复）
  void _syncWebSocketConnectionState() {
    final currentlyConnected = WebSocketConnectionManager.instance.isConnected;
    if (currentlyConnected) {
      setState(() {
        _isConnected = true;
        _currentServerName = WebSocketConnectionManager.instance.currentServerName;
        _isReconnecting = false;
        _reconnectAttempts = 0;
      });
      log.d('🔄 初始化时同步WebSocket连接状态: 已连接');
    }
  }

  /// 更新蓝牙连接状态
  void _updateBluetoothConnectionState() {
    final isConnected = _bleService.isConnected;
    final deviceName = _bleService.connectedDevice?.platformName ?? '';

    if (mounted) {
      setState(() {
        _isBluetoothConnected = isConnected;
        _connectedDeviceName = deviceName;
      });
    }

    log.d('🔵 蓝牙连接状态更新: $isConnected, 设备: $deviceName');
  }

  /// 处理BLE录音状态变化
  void _handleBleRecordStatus(RecordStatus status) {
    log.d('🔵 收到BLE录音状态: $status');

    switch (status) {
      case RecordStatus.recording:
        // BLE设备要求开始录音
        if (!_isRecording) {
          log.d('🔵 BLE触发开始录音');
          _toggleRecording();
        }
        break;
      case RecordStatus.idle:
        // BLE设备要求停止录音
        if (_isRecording) {
          log.d('🔵 BLE触发停止录音');
          _toggleRecording();
        }
        break;
      case RecordStatus.error:
        // BLE设备报告错误
        log.d('🔵 BLE设备报告错误');
        if (_isRecording) {
          _stopRecording();
        }
        break;
    }
  }

  /// 处理来自前台服务的动作请求
  void _handleForegroundServiceAction(String action) {
    log.d('🎯 收到前台服务动作请求: $action');

    switch (action) {
      case 'start_recording':
        if (!_isRecording) {
          _toggleRecording();
        }
        break;
      case 'stop_recording':
        if (_isRecording) {
          _toggleRecording();
        }
        break;
    }
  }

  @override
  void dispose() {
    _shouldStopReconnecting = true;
    WidgetsBinding.instance.removeObserver(this); // 移除生命周期监听

    // 停止音频播放和清理音频资源
    _isPlayingQueue = false;
    _audioPlayer.stop();
    _playerSubscription?.cancel();
    _audioPlayer.dispose();

    // 清理其他资源
    _recorderService.removeCallbacks('tts_screen');

    // 停止并清理前台服务
    _foregroundService.dispose();

    // 清理BLE服务监听
    _bleRecordStatusSubscription?.cancel();
    _bleConnectionStateSubscription?.cancel();

    // 释放WebSocket服务引用，而不是直接断开
    WebSocketConnectionManager.instance.releaseService();
    _textController.dispose();

    super.dispose();
  }

  /// 监听应用生命周期变化
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    switch (state) {
      case AppLifecycleState.resumed:
        // 应用回到前台
        log.d('📱 应用回到前台');
        _isAppInBackground = false;
        _handleAppResumed();
        break;
      case AppLifecycleState.paused:
        // 应用进入后台
        log.d('📱 应用进入后台');
        _isAppInBackground = true;
        _handleAppPaused();
        break;
      case AppLifecycleState.detached:
        // 应用完全关闭
        log.d('📱 应用完全关闭');
        _handleAppDetached();
        break;
      default:
        break;
    }
  }

  /// 处理应用回到前台
  void _handleAppResumed() {
    // 如果前台服务正在运行，停止它（因为应用回到前台了）
    if (_foregroundService.isRunning) {
      log.d('🎯 应用回到前台，停止前台录音服务');
      _foregroundService.stop();
    }

    // 同步WebSocket连接状态
    final currentlyConnected = WebSocketConnectionManager.instance.isConnected;
    if (currentlyConnected != _isConnected) {
      setState(() {
        _isConnected = currentlyConnected;
        if (currentlyConnected) {
          _currentServerName = WebSocketConnectionManager.instance.currentServerName;
          _isReconnecting = false;
          _reconnectAttempts = 0;
        }
      });
      log.d('🔄 同步WebSocket连接状态: $currentlyConnected');
    }

    // 如果仍然未连接，尝试重连
    if (!_isConnected && !_isReconnecting) {
      log.d('🔄 应用回到前台，检查并重连WebSocket');
      _manualReconnect();
    }
  }

  /// 处理应用进入后台
  void _handleAppPaused() {
    // 应用进入后台时，始终启动前台服务，以支持后台录音翻译功能
    log.d('🎯 应用进入后台，启动前台服务以支持后台录音翻译');
    _startForegroundService();

    // 注意：不停止TTS音频播放，让用户可以在后台继续听音频
    log.d('📱 应用进入后台，保持TTS音频播放');
  }

  /// 启动前台服务
  Future<void> _startForegroundService() async {
    try {
      // 启动前台服务
      final success = await _foregroundService.start();
      if (success) {
        // 启用后台录音功能
        _foregroundService.enableBackgroundRecording(isConnected: _isConnected);

        // 如果当前正在录音，通知前台服务
        if (_isRecording) {
          _foregroundService.notifyStartRecording(
            fromLanguage: _fromLanguage,
            toLanguage: _toLanguage,
          );
        }

        log.d('🎯 前台服务启动成功，支持后台录音翻译');
      } else {
        log.d('🎯 前台服务启动失败');
      }
    } catch (e) {
      log.d('🎯 启动前台服务失败: $e');
    }
  }

  /// 处理应用完全关闭
  void _handleAppDetached() {
    // 应用完全关闭时才断开WebSocket连接
    log.d('🔌 应用完全关闭，断开WebSocket连接');
    WebSocketConnectionManager.instance.forceDisconnect();
  }

  /// 加载保存的翻译设置
  void _loadSavedSettings() {
    try {
      // 获取所有设置的摘要
      final settings = TranslationSettings.instance.getAllSettings();
      log.d('📱 加载保存的翻译设置: $settings');

      // 如果是首次使用，显示提示
      if (TranslationSettings.instance.isFirstTime) {
        log.d('🎉 首次使用翻译功能，使用默认设置');
        TranslationSettings.instance.markNotFirstTime();
      }

      // 触发UI更新以反映加载的设置
      if (mounted) {
        setState(() {
          // 这里不需要做任何事情，因为getter会自动从TranslationSettings获取值
          // setState只是为了触发UI重建
        });
      }
    } catch (e) {
      log.d('⚠️ 加载翻译设置失败: $e');
    }
  }

  /// 初始化服务
  Future<void> _initializeServices() async {
    // 加载保存的翻译设置
    _loadSavedSettings();

    await _initializeTranslationService();
    _initializeRecorderService();
  }

  /// 初始化翻译服务
  Future<void> _initializeTranslationService() async {
    try {
      log.d('🌐 初始化翻译服务...');

      // 检查WebSocket管理器的当前连接状态
      final isAlreadyConnected = WebSocketConnectionManager.instance.isConnected;
      if (isAlreadyConnected) {
        setState(() {
          _isConnected = true;
          _currentServerName = WebSocketConnectionManager.instance.currentServerName;
        });
        log.d('✅ WebSocket已连接，同步状态');
      }

      // 设置回调函数
      _translationService.onConnected = () {
        if (mounted) {
          setState(() {
            _isConnected = true;
            _isReconnecting = false;
            _reconnectAttempts = 0; // 重置重连次数
            _currentServerName = _translationService.getServerName(); // 更新服务器名称
          });

          // 发送连接状态到前台服务
          _foregroundService.sendConnectionStatus(true);
          // 更新前台服务的后台录音状态
          _foregroundService.enableBackgroundRecording(isConnected: true);

          log.d('✅ 翻译服务连接成功');
        }
      };

      _translationService.onDisconnected = () {
        if (mounted) {
          setState(() {
            _isConnected = false;
          });

          // 发送连接状态到前台服务
          _foregroundService.sendConnectionStatus(false);
          // 更新前台服务的后台录音状态
          _foregroundService.enableBackgroundRecording(isConnected: false);

          log.d('🔌 翻译服务连接断开');

          // 如果不是手动断开且没有在重连中，且应用在前台，则尝试重连
          if (!_isReconnecting && _reconnectAttempts < _maxReconnectAttempts && !_isAppInBackground) {
            _attemptReconnect();
          } else if (_isAppInBackground) {
            log.d('🔄 应用在后台，暂停自动重连');
          }
        }
      };

     _translationService.onAsrUpdate = (text, asrSid, isLast) {
      // 发送ASR结果到前台服务
      _foregroundService.sendASRResult(text);

      setState(() {
        if (isLast) {
          // 如果是最终片段
          if (_hasIncompleteSegment) {
            // 替换正在构建的片段
            _recognizedSegments[_recognizedSegments.length - 1] = text;
          } else {
            // 添加新的完整片段
            _recognizedSegments.add(text);
          }
          _hasIncompleteSegment = false; // 标记为完成
          log.d('🎤 ASR识别完成: $text');
        } else {
          // 如果是中间片段
          if (_hasIncompleteSegment) {
            // 替换正在构建的片段
            _recognizedSegments[_recognizedSegments.length - 1] = text;
          } else {
            // 添加新的正在构建的片段
            _recognizedSegments.add(text);
            _hasIncompleteSegment = true; // 标记为正在构建
          }
          log.d('🎤 ASR识别中: $text (中间片段)');
        }

        _updateTextDisplay();
      });
    };

      _translationService.onTranslation = (text, asrSid, sourceLanguage, targetLanguage) {
        // 发送翻译结果到前台服务
        _foregroundService.sendTranslationResult(text);

        setState(() {
          // 翻译结果通常对应最新完成的ASR片段
          // 确保翻译片段数量与识别片段数量匹配
          if (_translatedSegments.length < _recognizedSegments.length) {
            // 添加新的翻译片段
            _translatedSegments.add(text);
          } else if (_translatedSegments.isNotEmpty) {
            // 更新最后一个翻译片段
            _translatedSegments[_translatedSegments.length - 1] = text;
          }

          _updateTextDisplay();
        });

        // 自动复制功能
        if (_autoCopy && text.isNotEmpty) {
          Clipboard.setData(ClipboardData(text: text));
        }

        log.d('🔤 翻译结果: $text');
      };

      _translationService.onTtsAudio = (audioUrl, asrSid) {
        log.d('🔊 收到TTS音频: $audioUrl');
        _lastTtsAudioUrl = audioUrl;

        // 将TTS音频加入两个队列
        _pendingTtsUrls.add(audioUrl);
        _allTtsUrls.add(audioUrl);

        // 如果用户未在录音且自动播放开启，且当前没有在播放队列，则开始播放队列
        if (!_isRecording && _autoPlayTts && !_isPlayingQueue) {
          _startPlayingQueue();
        }
      };

      _translationService.onError = (error) {
        log.d('❌ 翻译服务错误: $error');
        // 顶部状态指示器已显示连接状态，无需额外警告
      };

      _translationService.onSessionEnded = (message) {
        log.d('✅ 翻译会话结束: $message');
        if (mounted) {
          setState(() {
            _isTranslating = false;
          });
        }
      };

      // 连接服务器（如果尚未连接）
      if (!isAlreadyConnected) {
        await _translationService.connect();
        log.d('✅ 新建翻译服务连接完成');
      } else {
        log.d('✅ 复用现有翻译服务连接');
      }
    } catch (e) {
      log.d('❌ 翻译服务初始化失败: $e');
      _showError('翻译服务初始化失败，请检查网络连接');
    }
  }

  /// 尝试重连WebSocket服务
  Future<void> _attemptReconnect() async {
    if (_isReconnecting || _reconnectAttempts >= _maxReconnectAttempts || _shouldStopReconnecting) {
      return;
    }

    setState(() {
      _isReconnecting = true;
      _reconnectAttempts++;
    });

    log.d('🔄 尝试重连翻译服务 (第 $_reconnectAttempts 次)');

    // 等待重连延迟
    await Future.delayed(_reconnectDelay);

    if (!mounted || _shouldStopReconnecting) {
      setState(() => _isReconnecting = false);
      return;
    }

    try {
      // 尝试重新连接
      await _translationService.connect();
      log.d('✅ 重连成功');
    } catch (e) {
      log.d('❌ 重连失败: $e');

      setState(() => _isReconnecting = false);

      if (_reconnectAttempts >= _maxReconnectAttempts) {
        // 达到最大重连次数，显示错误
        if (mounted) {
          _showError('连接失败，已达到最大重试次数。请检查网络后手动重试。');
        }
      } else if (!_shouldStopReconnecting) {
        // 使用Future.delayed避免递归调用，防止栈溢出
        Future.delayed(const Duration(seconds: 1), () {
          if (!_shouldStopReconnecting && mounted) {
            _attemptReconnect();
          }
        });
      }
    }
  }

  /// 手动重连
  Future<void> _manualReconnect() async {
    if (_isReconnecting || _isConnected) return;

    // 重置重连控制状态和计数
    _shouldStopReconnecting = false;
    _reconnectAttempts = 0;
    await _attemptReconnect();
  }

  /// 开始播放TTS音频队列
  Future<void> _startPlayingQueue() async {
    if (_pendingTtsUrls.isEmpty || _isPlayingQueue) return;

    setState(() {
      _isPlayingQueue = true;
      _currentPlayingIndex = 0; // 重置播放索引
    });
    log.d('🎵 开始播放TTS音频队列，共 ${_pendingTtsUrls.length} 个音频');

    await _playNextTtsInQueue();
  }

  /// 播放队列中的下一个TTS音频
  Future<void> _playNextTtsInQueue() async {
    if (_currentPlayingIndex >= _pendingTtsUrls.length) {
      setState(() {
        _isPlayingQueue = false;
        _currentPlayingIndex = 0;
      });
      log.d('🎵 TTS音频队列播放完成');
      return;
    }

    final audioUrl = _pendingTtsUrls[_currentPlayingIndex];
    log.d('🔊 播放队列中的TTS音频 ($_currentPlayingIndex/${_pendingTtsUrls.length}): $audioUrl');

    try {
      // 取消之前的订阅
      await _playerSubscription?.cancel();
      _playerSubscription = null;

      // 播放音频
      await _audioPlayer.setUrl(audioUrl);
      await _audioPlayer.play();

      // 监听播放完成事件，添加超时处理
      _playerSubscription = _audioPlayer.playerStateStream
          .where((state) =>
              state.processingState == ProcessingState.completed ||
              state.processingState == ProcessingState.idle)
          .timeout(
            const Duration(seconds: 30),
            onTimeout: (sink) {
              log.d('⏰ TTS播放超时，跳到下一个音频');
              sink.close();
            },
          )
          .listen(
            (_) {
              if (mounted && _isPlayingQueue) {
                _currentPlayingIndex++; // 移动到下一个音频
                _playNextTtsInQueue();
              }
            },
            onError: (e) {
              log.d('❌ TTS播放监听错误: $e');
              if (mounted && _isPlayingQueue) {
                _currentPlayingIndex++; // 即使出错也移动到下一个
                _playNextTtsInQueue();
              }
            },
            onDone: () {
              // Stream关闭时的处理
              log.d('🔄 TTS播放监听已关闭');
            },
          );

    } catch (e) {
      log.d('❌ 播放TTS音频失败: $e');
      // 继续播放下一个
      if (mounted && _isPlayingQueue) {
        _currentPlayingIndex++;
        await _playNextTtsInQueue();
      }
    }
  }

  /// 初始化录音服务
  void _initializeRecorderService() {
    _recorderService.initialize(
      callbackId: 'tts_screen',
      onAudioData: (audioData) {
  // 发送音频数据到翻译服务
  if (_isConnected && _isRecording) {

    final opusFrames = AudioFormatHelper.convertPcmToOpusFramesForASR(audioData);
    // 逐个发送每一帧
    for (int i = 0; i < opusFrames.length; i++) {
      _translationService.sendAudioData(opusFrames[i]);
    }
  }
},
      onError: (error) {
        log.d('❌ 录音错误: $error');
        _showError('录音出现问题: $error');
        _stopRecording();
      },
      onStatusChanged: (status) {
        if (mounted) {
          setState(() {
            _isRecording = status == RecordingStatus.recording;
          });
        }
      },
    );
  }

  /// 重置翻译状态和文本
  void _resetTranslationState() {
    setState(() {
      _recognizedSegments.clear();
      _translatedSegments.clear();
      _hasIncompleteSegment = false;
      _lastTtsAudioUrl = '';
      _currentTranslatedText = '';
      _isTranslating = false;
    });
    _textController.clear();
    // 清空音频队列但保留已收到的音频
    _pendingTtsUrls.clear();
    _allTtsUrls.clear();
    _currentPlayingIndex = 0;
    _updateTextDisplay();
  }

  /// 开始录音和翻译
  Future<void> _startRecording() async {
    try {
      // 清空音频缓冲区，确保没有残留数据
      AudioFormatHelper.clearAudioBuffer();

      // 检查权限
      if (!await PermissionHelper.requestMicrophonePermission(context)) {
        _showError('需要麦克风权限才能录音');
        return;
      }

      if (!_isConnected) {
        if (_reconnectAttempts >= _maxReconnectAttempts) {
          _showError('翻译服务未连接，请点击重连按钮重试');
        } else {
          // 顶部状态指示器已显示重连状态，开始重连但不显示提示
          _manualReconnect();
        }
        return;
      }

      log.d('🎤 开始录音翻译...');

      // 停止当前正在播放的TTS队列
      if (_isPlayingQueue) {
        _isPlayingQueue = false;
        await _audioPlayer.stop();
        _playerSubscription?.cancel();
        setState(() => _isPlayingQueue = false);
        log.d('🛑 停止TTS队列播放，开始录音');
      }

      // 清空待播放队列（因为要开始新的录音会话）
      _pendingTtsUrls.clear();
      _allTtsUrls.clear();
      _currentPlayingIndex = 0;

      // 清空之前的文本和累积片段
      _resetTranslationState();

      // 开始翻译会话
      await _translationService.startFixedLanguageTranslation(
        from: _fromLanguage,
        to: _toLanguage,
        tsEnable: true,
        ttsEnable: _autoPlayTts,
        ttsGender: _useMaleVoice ? 'male' : 'female',
        asrFormat: 'rawopus', // 🎯 匹配HTML版本：Raw Opus (60ms帧)
      );

      // 开始录音
      if (mounted) {
        await _recorderService.startRecording(context);
      }

      setState(() => _isTranslating = true);

      // 停止当前音频播放
      await _audioPlayer.stop();

      log.d('✅ 录音翻译已开始');
    } catch (e) {
      log.d('❌ 开始录音翻译失败: $e');
      _showError('无法开始录音，请稍后重试');
    }
  }

  /// 停止录音和翻译
  Future<void> _stopRecording() async {
    try {
      log.d('🛑 停止录音翻译...');

      // 停止录音
      await _recorderService.stopRecording();

      // 结束翻译会话
      await _translationService.endTranslation();

      // 如果前台服务正在运行，通知它停止录音
      if (_foregroundService.isRunning) {
        _foregroundService.notifyStopRecording();
      }

      setState(() => _isRecording = false);

      log.d('✅ 录音翻译已停止');

      // 录音停止后，如果自动播放开启且有待播放的TTS音频，开始播放队列
      if (_autoPlayTts && _pendingTtsUrls.isNotEmpty && !_isPlayingQueue) {
        log.d('🎵 录音结束，开始播放 ${_pendingTtsUrls.length} 个待播放的TTS音频');
        await _startPlayingQueue();
      }

    } catch (e) {
      log.d('❌ 停止录音翻译失败: $e');
      // 即使失败，也要更新状态
      setState(() => _isRecording = false);
    }
  }

  /// 切换录音状态
  Future<void> _toggleRecording() async {
    if (_isRecording) {
      await _stopRecording();
    } else {
      await _startRecording();
    }
  }





  /// 切换语言
  void _switchLanguages() {
    setState(() {
      final temp = _fromLanguage;
      _fromLanguage = _toLanguage;
      _toLanguage = temp;
    });
  }

  /// 播放翻译文本
  void _playTranslatedText() {
    // 停止当前播放（如果正在播放）
    if (_isPlayingQueue) {
      _isPlayingQueue = false;
      _audioPlayer.stop();
      _playerSubscription?.cancel();
      setState(() => _isPlayingQueue = false);
      log.d('🛑 停止当前播放，准备重新开始');
    }

    if (_allTtsUrls.isNotEmpty) {
      // 如果有完整的音频队列，从第一个开始播放
      log.d('🎵 从第一个音频开始播放完整队列，共 ${_allTtsUrls.length} 个音频');
      // 重置播放队列为完整队列
      _pendingTtsUrls.clear();
      _pendingTtsUrls.addAll(_allTtsUrls);
      _startPlayingQueue();
    } else if (_lastTtsAudioUrl.isNotEmpty) {
      // 如果只有最后一个TTS音频，直接播放
      _playTtsAudio(_lastTtsAudioUrl);
    } else {
      if (mounted) {
        _showWarning('没有可播放的音频');
      }
    }
  }

  /// 播放TTS音频
  Future<void> _playTtsAudio(String audioUrl) async {
    try {
      log.d('🐛 🔊 正在播放TTS音频: $audioUrl');
      await _audioPlayer.setUrl(audioUrl);
      await _audioPlayer.play();
    } catch (e) {
      log.d('❌ 播放TTS音频失败: $e');
      if (mounted) {
        _showWarning('播放音频失败，请重试');
      }
    }
  }

  /// 复制文本
  void _copyText() {
    String contentToCopy = '';
    final originalText = _textController.text;
    final translatedText = _currentTranslatedText;

    if (originalText.isNotEmpty && translatedText.isNotEmpty) {
      // 有原文和译文，都复制
      contentToCopy = '$originalText\n\n$translatedText';
    } else if (translatedText.isNotEmpty) {
      // 只有译文，复制译文
      contentToCopy = translatedText;
    } else if (originalText.isNotEmpty) {
      // 只有原文，复制原文
      contentToCopy = originalText;
    }

    if (contentToCopy.isNotEmpty) {
      Clipboard.setData(ClipboardData(text: contentToCopy));
      // 显示复制成功提示
      if (mounted) {
        _showSuccess('已复制到剪贴板');
      }
    } else {
      if (mounted) {
        _showWarning('没有可复制的文本');
      }
    }
  }

  /// 清空文本
  void _clearText() {
    // 停止当前播放和清理音频队列
    _isPlayingQueue = false;
    _audioPlayer.stop();
    _playerSubscription?.cancel();

    // 清空队列和状态
    _pendingTtsUrls.clear();
    _allTtsUrls.clear();
    _currentPlayingIndex = 0;
    setState(() => _isPlayingQueue = false);
    _resetTranslationState();
  }

  /// 更新文本显示
  void _updateTextDisplay() {
    // 更新原文显示（输入框中的内容）
    if (_recognizedSegments.isNotEmpty) {
      _textController.text = _recognizedSegments.join('');
    }

    // 更新译文显示
    if (_translatedSegments.isNotEmpty) {
      setState(() {
        _currentTranslatedText = _translatedSegments.join('');
      });
    }
  }

  /// 显示成功消息
  void _showSuccess(String message) {
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: Colors.green,
          duration: const Duration(seconds: 2),
        ),
      );
    }
  }

  /// 显示警告消息（橙色，用于非关键问题）
  void _showWarning(String message) {
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: Colors.orange,
          duration: const Duration(seconds: 2),
        ),
      );
    }
  }

  /// 显示错误消息（红色，仅用于关键错误）
  void _showError(String message) {
    if (mounted) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text(message),
          backgroundColor: Colors.red,
          duration: const Duration(seconds: 3),
          action: SnackBarAction(
            label: '关闭',
            textColor: Colors.white,
            onPressed: () {
              ScaffoldMessenger.of(context).hideCurrentSnackBar();
            },
          ),
        ),
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('语音翻译'),
        actions: [
          // 重连按钮
          if (!_isConnected && !_isReconnecting)
            IconButton(
              icon: const Icon(Icons.refresh, size: 20),
              onPressed: _manualReconnect,
              tooltip: '重新连接',
            ),
          // 蓝牙和连接状态栏
          Expanded(
            child: BluetoothStatusBar(
              isBluetoothConnected: _isBluetoothConnected,
              isWebSocketConnected: _isConnected,
              deviceName: _connectedDeviceName.isNotEmpty ? _connectedDeviceName : null,
              pingLatency: -1, // 使用默认延迟显示
              onBluetoothTap: () {
                Navigator.pushNamed(context, '/settings');
              },
              onWebSocketTap: () {
                // WebSocket重连
                if (!_isConnected && !_isReconnecting) {
                  _manualReconnect();
                }
              },
            ),
          ),
          const SizedBox(width: 16),
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            const SizedBox(height: 16),

            // 翻译输入组件
            Container(
              margin: const EdgeInsets.symmetric(horizontal: 16),
              child: TranslationInput(
                controller: _textController,
                onClear: () {
                  _clearText();
                },
                onListening: _toggleRecording,
                isListening: _isRecording,
                isTranslating: _isTranslating,
                translatedText: _currentTranslatedText.isNotEmpty ? _currentTranslatedText : null,
                showTranslationOnly: _onlyShowTranslation,
                onPlayTranslation: () {
                  _playTranslatedText();
                },
                onCopyText: () {
                  _copyText();
                },
              ),
            ),

            const SizedBox(height: 16),

            // 语言选择区域
            _buildLanguageSelectionSection(),

            const SizedBox(height: 16),

            // 设置区域
            _buildSettingsSection(),

            const SizedBox(height: 16),

            const SizedBox(height: 20), // 底部空间
          ],
        ),
      ),
    );
  }

  /// 构建语言选择区域
  Widget _buildLanguageSelectionSection() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      child: LanguageSelector(
        sourceLanguage: _fromLanguage,
        targetLanguage: _toLanguage,
        onSwap: _switchLanguages,
        onSourceLanguageChanged: (String language) {
          setState(() {
            _fromLanguage = language;
          });
          log.d('🌐 源语言已更改为: $language');
        },
        onTargetLanguageChanged: (String language) {
          setState(() {
            _toLanguage = language;
          });
          log.d('🌐 目标语言已更改为: $language');
        },
        isCompact: false,
      ),
    );
  }

  /// 构建设置区域
  Widget _buildSettingsSection() {
    return Container(
      margin: const EdgeInsets.symmetric(horizontal: 16),
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: Colors.grey[300]!),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(Icons.settings, color: Colors.blue[600], size: 16),
              const SizedBox(width: 6),
              const Text(
                '翻译设置',
                style: TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          // 第一行：自动播放、使用男声
          Row(
            children: [
              Expanded(child: _buildCompactSwitchRow('自动播放', _autoPlayTts, (value) {
                setState(() => _autoPlayTts = value);
              })),
              const SizedBox(width: 16),
              Expanded(child: _buildCompactSwitchRow('使用男声', _useMaleVoice, (value) {
                setState(() => _useMaleVoice = value);
              })),
            ],
          ),
          const SizedBox(height: 4),
          // 第二行：仅显示译文、自动复制
          Row(
            children: [
              Expanded(child: _buildCompactSwitchRow('仅显示译文', _onlyShowTranslation, (value) {
                setState(() => _onlyShowTranslation = value);
              })),
              const SizedBox(width: 16),
              Expanded(child: _buildCompactSwitchRow('自动复制', _autoCopy, (value) {
                setState(() => _autoCopy = value);
              })),
            ],
          ),
          const SizedBox(height: 8),
          // 服务器状态显示
          Row(
            children: [
              Icon(Icons.dns, color: Colors.grey[600], size: 16),
              const SizedBox(width: 6),
              const Text(
                '当前服务器',
                style: TextStyle(fontSize: 14),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Container(
                  height: 36,
                  padding: const EdgeInsets.symmetric(horizontal: 12),
                  decoration: BoxDecoration(
                    color: Colors.grey[50],
                    border: Border.all(color: Colors.grey[300]!),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: Row(
                    children: [
                      Expanded(
                        child: Text(
                          _currentServerName.isNotEmpty ? _currentServerName : '连接中...',
                          style: const TextStyle(fontSize: 13, color: Colors.black87),
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ],
      ),
    );
  }

  /// 构建紧凑开关行
  Widget _buildCompactSwitchRow(String title, bool value, Function(bool) onChanged) {
    return Padding(
      padding: const EdgeInsets.symmetric(vertical: 4),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: [
          Expanded(
            child: Text(
              title,
              style: const TextStyle(fontSize: 14),
              overflow: TextOverflow.ellipsis,
            ),
          ),
          const SizedBox(width: 8),
          Switch(
            value: value,
            onChanged: onChanged,
            activeColor: Colors.blue[600],
            activeTrackColor: Colors.blue[200],
            inactiveThumbColor: Colors.grey[400],
            inactiveTrackColor: Colors.grey[300],
            materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
          ),
        ],
      ),
    );
  }
}